<template>
  <div class="deadline-table">
    <div v-if="!disabled">
      <el-button
        type="primary"
        size="small"
        icon="Edit"
        @click="deadlineAutocompleteDialog.show()"
      >
        批量添加
      </el-button>
      <el-button
        type="primary"
        size="small"
        icon="Plus"
        @click="deadlineDialog.show()"
      >
        添加
      </el-button>
      <el-button
        type="danger"
        size="small"
        icon="Delete"
        :disabled="selectedData.length === 0"
        @click="handleDeleteRow()"
      >
        删除
      </el-button>
    </div>
    <Table
      :data="model"
      @selection-change="handleSelectionChange"
      :select-column="!disabled"
      max-height="300px"
    >
      <TableColumn label="期限" :width="150">
        <template #default="{ row }">
          {{ formatDateStr(row.deadlineDate, 'YYYY年MM月DD日') }}
        </template>
      </TableColumn>
      <TableColumn label="关键期限" :min-width="40">
        <template #default="{ row }">
          <KeyShow :status="row.isKey" />
        </template>
      </TableColumn>
      <TableColumn
        label="期限要求"
        prop="deadlineRequire"
        width="auto"
        align="left"
        header-align="left"
      />
      <TableColumn v-if="!disabled" label="操作" :width="180">
        <template #default="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            :disabled="disabled"
            @click="deadlineDialog.show(row, $index)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            size="small"
            icon="Delete"
            :disabled="disabled"
            @click="handleDeleteRow(row, $index)"
          >
            删除
          </el-button>
        </template>
      </TableColumn>
    </Table>
    <DeadlineDialog
      ref="deadlineDialog"
      @add="addTableData"
      @update="updateTableData"
    />
    <DeadlineAutocompleteDialog
      ref="deadlineAutocompleteDialog"
      @update="addTableData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, useTemplateRef } from 'vue'
import TableColumn from '@/components/table/TableColumn.vue'
import Table from '@/components/table/Table.vue'
import { formatDateStr, getDate } from '@/plugins/date'
import DeadlineAutocompleteDialog from '@/views/mission/task/thing/DeadlineAutocompleteDialog.vue'
import DeadlineDialog from '@/views/mission/task/thing/DeadlineDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import KeyShow from '@/components/statusShow/key/KeyShow.vue'

const deadlineDialog =
  useTemplateRef<InstanceType<typeof DeadlineDialog>>('deadlineDialog')
const deadlineAutocompleteDialog = useTemplateRef<
  InstanceType<typeof DeadlineAutocompleteDialog>
>('deadlineAutocompleteDialog')

const { disabled } = defineProps<{
  disabled: boolean
}>()

const model = defineModel<any[]>()
const selectedData = ref([])

function handleSelectionChange(rows: any[]) {
  selectedData.value = rows
}

// 期限重复提示
function repeatDeadlineDate(rows: any) {
  const temp = model.value
  const deadlineTimes = rows.map((item) => item.deadlineDate)
  for (let i = 0; i < temp?.length; i++) {
    const item = temp[i]
    if (deadlineTimes.includes(item.deadlineDate)) {
      ElMessage.error('当前期限已添加，请重新添加其他期限')
      return false
    }
  }
  return true
}

function addTableData(rows: any[]) {
  const temp = model.value
  if (!repeatDeadlineDate(rows)) return
  temp.push(
    ...rows.map((item) => {
      return {
        deadlineDate: item.deadlineDate,
        isKey: item.isKey,
        deadlineRequire: item.deadlineRequire,
      }
    }),
  )
  temp.sort((a, b) => {
    return getDate(a.deadlineDate).getTime() - getDate(b.deadlineDate).getTime()
  })
  model.value = temp
}

function handleDeleteRow(row?: any, index?: number) {
  let text = ''
  if (row && row.deadlineDate) {
    text = `确定要删除【期限：${row.deadlineDate}】吗？`
  } else if (selectedData.value.length !== 0) {
    text = `确定要删除 ${selectedData.value.length} 条数据吗？`
  }
  if (text) {
    ElMessageBox.confirm(text, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      if (row) {
        model.value = model.value.toSpliced(index, 1)
      } else {
        model.value = model.value.filter((item) => {
          return !selectedData.value.includes(item)
        })
      }
    })
  }
}

function updateTableData(row: any, index: number) {
  model.value[index] = {
    deadlineDate: row.deadlineDate,
    isKey: row.isKey,
    deadlineRequire: row.deadlineRequire,
  }
}
</script>

<style scoped lang="scss">
.deadline-table {
  width: 100%;
}
</style>
